"""
@Author : 合肥一元数智教育科技有限公司
@Date :  2025/5/15 15:53
@Description : 

"""
from django.core.paginator import Paginator

from django2511 import settings


def page_utile(request, data_list):
    # 创建一个分页对象  参数1  所有数据  参数2  每页显示的数据条数
    paginator = Paginator(data_list, settings.PAGE_SIZE)
    # 数据总条数
    total_count = paginator.count
    # 总页数
    total_pages = paginator.num_pages
    # 页码区间
    page_range = paginator.page_range

    # 获取当前页对象  获取当前页数据  前端传递  page 1  2
    page = request.GET.get('page', 1)
    current_page = paginator.page(page)
    # 获取下一页的页码
    try:
        next_page = current_page.next_page_number()
    except Exception as e:
        next_page = total_pages
    # 上一页页码
    try:
        pre_page = current_page.previous_page_number()
    except Exception as e:
        pre_page = 1
    # 判定是否有下一页
    has_next = current_page.has_next()
    # 判定是否有上一页
    has_previous = current_page.has_previous()
    # 获取当前页数据
    table_data = current_page.object_list
    # 获取当前页的页码
    current_page_number = current_page.number
    # 组装分页数据
    context = {
        'table_data': table_data,
        'current_page_number': current_page_number,
        'page_range': custom_page_range(total_pages, current_page_number),
        'total_pages': total_pages,
        'total_count': total_count,
        'has_previous': has_previous,
        'has_next': has_next,
        'pre_page': pre_page,
        'next_page': next_page,
    }
    return context


# 生成分页区间  total_pages  总页数     current_page_number 当前页码    nav_size 分页器显示的页码个数
def custom_page_range(total_pages, current_page_number, nav_size=settings.NAV_SIZE):
    min = current_page_number - nav_size // 2
    min = min if min > 1 else 1
    max = min + nav_size - 1
    max = max if max < total_pages else total_pages
    return range(min, max + 1)
